package com.zhiyin.game.websocket;


import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.util.Map;

@ServerEndpoint("/webSocket")
@Component
public class WebSocketServer {

    private static Logger logger = LoggerFactory.getLogger(WebSocketServer.class);
    private Session session;
    private static WebSocketServer webSocketServer = new WebSocketServer();

    @OnOpen
    public void onOpen(Session session) {
        webSocketServer.session = session;
    }

    @OnMessage
    public void onMessage(String message, Session session) throws Exception {
        logger.info("报文:" + message);
    }

    @OnError
    public void OnError(Session session, Throwable error) {
        logger.error("原因:" + error.getMessage());
        error.printStackTrace();
    }

    @OnClose
    public void onClose() {
        logger.info("关闭socket");
    }

    public static void sendMessage(Map<String, Object> message) {
        try {
            webSocketServer.session.getBasicRemote().sendText(JSON.toJSONString(message));
        } catch (Exception e) {
            logger.error("sendMessage catch exception", e);
        }
    }

}
